<template>
  <div>
    <h3>角色列表组件</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="isAddRoles = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <!-- 角色列表表格 -->
    <el-table :data="rolesList" border>
      <!-- 添加展开列 -->
      <el-table-column label="#" type="expand">
        <template slot-scope="scope">
          <!-- 一级权限 -->
          <el-row
            v-for="(item, index) in scope.row.children"
            :key="item.id"
            :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vcenter']"
          >
            <el-col :span="5">
              <el-tag
                closable
                @close="removeTag(scope.row, item.id, scope.row)"
              >
                {{ item.authName }}
              </el-tag>
              <i class="el-icon-right"></i>
            </el-col>
            <el-col :span="19">
              <!-- 二级权限 -->
              <el-row
                v-for="(item1, index) in item.children"
                :key="item1.id"
                :class="[
                  index === item.children.length - 1 ? '' : 'bdbottom',
                  'vcenter',
                ]"
              >
                <el-col :span="5">
                  <el-tag
                    type="success"
                    closable
                    @close="removeTag(scope.row, item1.id, item)"
                  >
                    {{ item1.authName }}
                  </el-tag>
                  <i class="el-icon-right"></i>
                </el-col>
                <!-- 三级权限 -->
                <el-col :span="19">
                  <el-tag
                    type="warning"
                    v-for="item2 in item1.children"
                    :key="item2.id"
                    closable
                    @close="removeTag(scope.row, item2.id, item1)"
                  >
                    {{ item2.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="No." type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <!-- 三个操作button -->
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editRole(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="deleteRole(scope.row.id)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-setting"
            @click="setRights(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 点击添加角色提示框 -->
    <el-dialog
      title="提示"
      :visible.sync="isAddRoles"
      width="30%"
      :before-close="handleClose"
      @close="onClose"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addModel"
        :rules="addRules"
        ref="addRoleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addModel.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addModel.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddRoles = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="isShareRights"
      width="50%"
      @close="onClose"
    >
      <!-- 表单区域 -->
      <el-form ref="ShareRightsForm" label-width="100px" class="demo-ruleForm">
        <el-tree
          :data="rightsList"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          @close="setRightDialogClose"
          ref="RightsTree"
          :props="{
            label: 'authName',
            children: 'children',
          }"
        ></el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShareRights = false">取 消</el-button>
        <el-button type="primary" @click="sendRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击修改用户信息提示框 -->
    <el-dialog
      title="提示"
      :visible.sync="isEditShow"
      width="50%"
      @close="onClose"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editModel"
        :rules="addRules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editModel.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editModel.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditShow = false">取 消</el-button>
        <el-button type="primary" @click="doEidt">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Service } from '../service/index'
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 权限树
      rightsList: [],
      // 定义添加用户时数据验证
      addRules: {
        rolesName: [
          { required: true, message: '请输入角色名~亲', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在3到15个字符~亲',
            trigger: 'blur',
          },
        ],
        rolesInfo: [
          { required: true, message: '请输入角色描述哦~亲', trigger: 'blur' },
          {
            min: 7,
            max: 30,
            message: '长度在7到30个字符~亲',
            trigger: 'blur',
          },
        ],
      },
      // 开启编辑弹窗
      isEditShow: false,
      // 开启添加弹窗
      isAddRoles: false,
      // 开启分配权限弹窗
      isShareRights: false,
      // 定义添加用户数据
      addModel: {
        roleName: '',
        roleDesc: '',
      },
      //设置树形控件中默认选中的内容
      defKeys: [],
      //保存正在操作的角色id
      roleId: '',
      // 定义编辑用户数据
      editModel: {
        roleName: '',
        roleDesc: '',
        id: -1,
      },
    }
  },
  async created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表数据
    async getRolesList() {
      const res = await Service.getRoles()
      this.rolesList = res.data.data
    },
    // 展示编辑用户的对话框
    editRole(data) {
      this.isEditShow = true
      this.editModel.roleName = data.roleName
      this.editModel.roleDesc = data.roleDesc
      this.editModel.id = data.id
    },
    // 确认修改
    async doEidt() {
      this.isEditShow = false
      let a = { ...this.editModel }
      const res = await Service.editRoles(a.id, a.roleName, a.roleDesc)
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        this.getRolesList()
      }
    },
    // 添加角色
    addRole() {
      // 点击时校验数据
      this.$refs.addRoleForm.validate(async (isOk) => {
        // 成功
        if (isOk) {
          const res = await Service.addRoles(this.addModel)
          if (res.data.meta.status !== 201) {
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message.success(res.data.meta.msg)
            this.rolesList.push(res.data.data)
            this.isAddRoles = false
          }
        } else {
          this.$message.error('对不起信息未通过校验')
        }
      })
    },
    // 关闭弹窗
    onClose() {
      this.$refs.addRoleForm && this.$refs.addRoleForm.resetFields()
    },
    // 点击弹窗x号的弹出确认提示框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 删除角色下的权限
    async removeTag(data, id, father) {
      // 确认删除提示
      try {
        const res = await this.$msgBox.confirm(
          '删除数据后不可恢复,你是否还要继续',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        if (res === 'confirm') {
          const resdata = await Service.removeRights(data.id, id)
          if (resdata.data.meta.status !== 200) {
            this.$message.error('请求错误')
          } else {
            this.$message.success('删除权限成功')
            const fIndex = father.children.findIndex((e) => e.id == id)
            fIndex > -1 && father.children.splice(fIndex, 1)
          }
        }
      } catch (error) {
        this.$message.error('取消操作成功')
      }
    },
    // 点击分配权限
    async setRights(data) {
      this.isShareRights = true
      this.$set(this.defKeys, [])
      const res = await Service.getRightsTree()
      this.rightsList = res.data.data
      this.roleId = data.id
      this.getLefKeys(data, this.defKeys)
    },
    // 定义递归获取已被选中的权限的id
    getLefKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach((item) => {
          this.getLefKeys(item, arr)
        })
      }
    },
    // 权限分配弹窗关闭操作
    setRightDialogClose() {
      this.defKeys = []
    },
    // 选择权限,并提交到数据库
    async sendRights() {
      this.isShareRights = false
      const keys = [
        ...this.$refs.RightsTree.getCheckedKeys(),
        ...this.$refs.RightsTree.getHalfCheckedKeys(),
      ]
      const keyStr = keys.join(',')
      const res = await Service.setNewRights(this.roleId, keyStr)
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        this.getRolesList()
      }
    },
    // 删除角色
    async deleteRole(id) {
      try {
        await this.$msgBox.confirm('删除数据后不可恢复,您还要继续么', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        const res = await Service.deleteRole(id)
        if (res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg)
        } else {
          this.$message.success(res.data.meta.msg)
          this.getRolesList()
        }
      } catch (error) {
        console.log(error)
      }
    },
  },
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>